#!/bin/bash

SWNAME=spark-store
PKNAME=spark-store
SWVER=4.7.0-1

# 注意安装顺序，后装者依赖前装者
DEB_PATH1=./downloads/${SWNAME}.deb

DIR_DESKTOP_FILES=/usr/share/applications
DSK_FILE=${SWNAME}.desktop
DSK_PATH=${DIR_DESKTOP_FILES}/${DSK_FILE}
# app_dir=/opt/Motrix

action=$1
if [ "$action" == "" ]; then action=安装; fi

. ./scripts/common.sh

function sw_download() {
	# tmpdns=`cd /exbin && droidexec ./vm_getHostByName.sh docs.qq.com`
	# exit_if_fail $? "DNS解析失败"
	# echo "$tmpdns" >> /etc/hosts

	for i in 1 2 3
	do
	gxmessage -title "是否继续安装？" $'\n系统损坏提示: \n星火应用商店很大概率会破坏当前系统, 它并不是为proot环境设计的\n损坏后你需要重新安装虚拟系统, 请确认是否继续安装\n\n'  -center -buttons "继续安装$i/3:0,取消安装:1"
	case "$?" in
		"0")
			:
			;;
		*) 
			echo "您已取消安装"
			exit 1
			;;
	esac
	done

	case "${CURRENT_VM_ARCH}" in
		"arm64")
			swUrl="https://gitee.com/spark-store-project/spark-store/releases/download/4.7.0/spark-store_${SWVER}_arm64.deb"
			download_file2 "${DEB_PATH1}" "${swUrl}"
			exit_if_fail $? "下载失败，网址：${swUrl}"
		;;
		"amd64")
			swUrl="https://gitee.com/spark-store-project/spark-store/releases/download/4.7.0/spark-store_${SWVER}_arm64.deb"
			download_file2 "${DEB_PATH1}" "${swUrl}"
			exit_if_fail $? "下载失败，网址：${swUrl}"
		;;
		*) exit_unsupport ;;
	esac
}

function sw_install() {

	# mkdir ${ZZSWMGR_APPI_DIR}/alist
	# mkdir -p ${app_dir}

	apt-get install -y libasound2t64
	exit_if_fail $? "依赖包安装失败"

	echo "正在安装. . ."
	install_deb ${DEB_PATH1}
	exit_if_fail $? "安装失败，软件包：${DEB_PATH1}"

}

function sw_create_desktop_file() {
	echo "正在生成桌面文件"


	# sed -i 's|Exec="/opt/腾讯文档/tdappdesktop" %U|Exec="/opt/腾讯文档/tdappdesktop"  --no-sandbox %U|'    ${DSK_PATH}

	tmpfile=${DSK_PATH}
	cp2desktop ${tmpfile}

	# tmpfile=${DIR_DESKTOP_FILES}/${SWNAME}.desktop
	# cat <<- EOF > ${tmpfile}
	# 	[Desktop Entry]
	# 	Name=${SWNAME}
	# 	GenericName=${SWNAME}
	# 	Exec=${SWNAME}
	# 	Terminal=false
	# 	Type=Application
	# 	Icon=/usr/share/icons/hicolor/128x128/apps/motrix.png
	# EOF
	# cp2desktop ${tmpfile}

	# echo "正在生成启动脚本"
	# mv -f /usr/bin/${SWNAME} /usr/bin/${SWNAME}.bak
	# tmpfile=/usr/bin/${SWNAME}
	# cat <<- EOF > ${tmpfile}
	# 	#!/bin/bash
	# 	exec ${app_dir}/motrix --no-sandbox
	# EOF
	# exit_if_fail $? "启动脚本生成失败"
	# chmod 755 ${tmpfile}

	gxmessage -title "提示"     $'\n安装完成\n\n'  -center
}

function sw_remove() {
	[ "${PKNAME}" != "" ] || exit_if_fail $? "sw_remove 失败"

	apt-get -y purge "${PKNAME}"
	apt-get -y autoremove --purge "${PKNAME}"
	dpkg --remove --force-remove-reinstreq "${PKNAME}"

	echo "正在删除桌面图标"
	rm2desktop "${PKNAME}"*
	
	echo "正在删除软件图标"
	rm -rf /usr/share/applications/"${PKNAME}"*

	echo "正在删除相关配置文件"
	rm -rf /home/${ZZ_USER_NAME}/.local/share/Kingsoft
	rm -rf /home/${ZZ_USER_NAME}/.config/Kingsoft

	echo "正在删除主安装文件夹"
	rm -rf /opt/durapps/spark-store

	echo "正在删除软件的卸载脚本"
	rm -rf /var/lib/dpkg/info/"${PKNAME}"*

	apt-get clean
}

if [ "${action}" == "卸载" ]; then
	# echo "暂不支持卸载"
	# exit 1
	sw_remove
else
	sw_download
	sw_install
	sw_create_desktop_file
fi

